// GitHub - tutorialworks/pipeline-library-demo: Demonstration of using a shared library in Jenkins
// https://github.com/tutorialworks/pipeline-library-demo
@Library('pipeline-shared-libraries')_


def parallelStages = [:]
def projectsToBuild = []

pipeline {
    agent {
        node {
            label '172.22.27.211_Automation'
        // customWorkspace "/home/workspace/Testproj/Automation/BMCQATests/test-pipline-job"
        }
    }

    parameters  {
        file(name: 'config_zip', description: 'config.zip:each file named with "host.cfg" in config.zip, example:172.22.27.162.cfg')
    }

    environment {
        time = '1'
        config_folder = "config_folder"
        py_basename = ""
        cfg_basename = ""
        new_test_py_name = ""
    }

    stages {
        stage('Build') {
            steps {
                echo "unstashParam: ${config_zip}"
                // upload parameter file
                unstashParam "config_zip"


                sh(script:"""
                set +x
                echo "unzip  ${config_zip} ..."
                unzip ${config_zip} -d $config_folder && mv $config_folder/* .
                """, returnStatus:true)


                // script {
                //     echo 'Pull Code......'
                //     def scmVars = checkout([$class: 'SubversionSCM', additionalCredentials: [], excludedCommitMessages: '', excludedRegions: '', excludedRevprop: '', excludedUsers: '', filterChangelog: false, ignoreDirPropChanges: false, includedRegions: '', locations: [[cancelProcessOnExternalsFail: true, credentialsId: 'fccf73fd-e7ce-45d9-a2f9-80eb11dccab1', depthOption: 'infinity', ignoreExternalsOption: true, local: '.', remote: 'http://172.22.27.2:9999/scm/svn/SRD_Auto_For_Jenkins/BMCQATests']], quietOperation: true, workspaceUpdater: [$class: 'UpdateUpdater']])
                //     svnversion = scmVars.SVN_REVISION
                //     echo '${svnversion}'

                // }

            }
        }



        stage("Test") {
            steps {
                script { 
                    
                    // Find directories (for simplicity’s sake, all directories)
                    def cfg_list = findFiles(glob: '*.cfg')
                    println "cfg_list: ${cfg_list}"
                    cfg_list.each { f ->
                        projectsToBuild.add(f.name)
                    }
                    
                    println "projectsToBuild : $projectsToBuild"

                    def py_list = findFiles(glob: 'test_*.py')
                    println "py_list: ${py_list}"
                    
                    projectsToBuild.each { cfg ->
                        parallelStages[cfg] = {
                            stage(cfg) {
                                // cfg_basename = sh(script:"echo $cfg | sed -r s#.cfg##", returnStdout:true).trim()
                                
                                for(py in py_list){
                                    // py_basename = sh(script:"echo $py | sed -r s#.py##", returnStdout:true).trim()
                                    //new_test_py_name = "$cfg-$py"
                                    new_test_py_name = sh(script:"set +x;echo `echo $cfg | sed -r s#.cfg##`-`echo $py | sed -r s#.py##`.py", returnStdout:true).trim()
                    
                                    sh("""
                                    set +x
                                    echo "Generate ${new_test_py_name} with $cfg and $py"
                                    echo config_text = \\'\\'\\' >   ${new_test_py_name}
                                    cat $cfg >>  ${new_test_py_name}
                                    echo \\'\\'\\' >>  ${new_test_py_name}
                                    echo "import os"  >> ${new_test_py_name}
                                    echo "os.environ['config_text'] = config_text"  >> ${new_test_py_name}
                                    echo "\n\n" >>  ${new_test_py_name}
                                    cat $py >> ${new_test_py_name}
                    
                                    
                                    python3 $new_test_py_name
                                    
                    
                                    """)
                                    println "############ End Test $new_test_py_name ##############"
                    
                                    
                                }
                            }
                        }
                    }
                    
                    parallel parallelStages
                }
            }
        }

    }

    post {
        always {
            // junit '**/target/*.xml'
            echo "remove all new_test_py_name"
            sh(script:"set +x;rm -rf *-*.py")
            echo 'Finished'
        }
        failure {
            // mail to: team@example.com, subject: 'The Pipeline failed :('
            echo 'The Pipeline failed :('
        }
    }
}
